<template>
  <div id="imgResultTemplate">
    <Breadcrumb content="图文报告模版维护" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="15">
          <vxe-table ref="rptGroupTableRef" class="mytable-scrollbar" border align="left" height="auto" :data="rptGroupList" :loading="rptGroupLoading" @current-change="clickRowSelect" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true, keyField: 'id' }" :column-config="{ resizable: true }" :tree-config="{
              expandAll: true,
              rowField: 'id'
            }" resizable show-overflow keep-source :reserve="true">
            >
            <vxe-column field="code" title="编码" tree-node sortable></vxe-column>
            <vxe-column field="name" title="名称" sortable></vxe-column>
          </vxe-table>
        </Pane>

        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">模版维护</div>
              <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findTemplateList" @keyup="keyupEnter" @search-click="handleSearch(searchForm.searchValue)"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="qloading" :disabled="disabledTag" @click="findTemplateList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addTemplate"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table ref="templateTableRef" class="mytable-scrollbar" border="inner" align="left" height="auto" :data="templateList" :loading="qloading" @current-change="templateRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column field="templateCode" title="模版编码" width="100"> </vxe-column>
              <vxe-column field="templateName" title="模版名称" width="150"> </vxe-column>
              <vxe-column field="sampleTypeNa" title="样本类型"></vxe-column>
              <vxe-column field="seq" title="顺序号"></vxe-column>
              <vxe-column field="isAutoApply" title="是否自动应用" min-width="80" align="center" checked-value="0" unchecked-value="1">
                <template #default="{ row }">
                  <el-tag :type="getIsStaticTagType(row)">{{ getIsStaticStatusDesc(row) }}</el-tag>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>

        <Pane size="55">
          <Splitpanes horizontal class="horizontalLine">
            <Pane :size="useSize === 'small' ? 34 : useSize === 'default' ? 40 : 45">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="toolbartitle">模版详情</div>
                </template>
                <template #tools>
                  <vxe-button type="text" class="button-blue margin-right-sm" @click="saveTemplateAndItem('templateFormRef')" icon="vxe-icon-square-plus" :disabled="sltRptGroup.id !== null && sltRptGroup.id !== '' && sltRptGroup.id !== undefined" content="保存"></vxe-button>
                </template>
              </vxe-toolbar>
              <el-form ref="templateFormRef" :model="templateForm" :rules="templateFormRule" label-width="110px" inline-message v-loading="qloading">
                <el-form-item prop="id" label="模版ID">
                  <el-input type="text" v-model="templateForm.id" disabled></el-input>
                </el-form-item>
                <el-form-item prop="templateCode" label="编码">
                  <el-input type="text" v-model="templateForm.templateCode"></el-input>
                </el-form-item>
                <el-form-item prop="templateName" label="名称">
                  <el-input type="text" v-model="templateForm.templateName"></el-input>
                </el-form-item>
                <el-row>
                  <el-col span="12">
                    <el-form-item prop="sampleType" label="样本类型">
                      <SelectDataList ref="employeeSelectRef" :url="'/api/lab/labSampleType/findSampleTypeList'" :displayField="[
                          { title: '编码', props: 'sampleTypeCode' }, //列标题
                          { title: '名称', props: 'sampleTypeName' }
                        ]" :searchParam="{ code: 'spectype' }" :placeholder="'点击选择样本类型'" @selectDataRow="SelectRowClick1" v-model="templateForm.sampleType" @clearValue="clearValueHandler" @sliceValue="sliceHandler" />
                    </el-form-item>
                  </el-col>
                  <el-col span="12">
                    <el-form-item label="顺序号" prop="seq">
                      <el-input-number v-model="templateForm.seq" :min="1" :max="500" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <!--<el-form-item label="是否合并组合模板" prop="isMerge">
                  <vxe-switch v-model="templateForm.isMerge" inline-prompt open-label="是" close-label="否" open-value="1" close-value="1"></vxe-switch>
                </el-form-item> -->
                <el-form-item label="是否自动应用" prop="isAutoApply">
                  <vxe-switch v-model="templateForm.isAutoApply" inline-prompt open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                </el-form-item>
              </el-form>
            </Pane>

            <Pane :size="useSize === 'small' ? 66 : useSize === 'default' ? 60 : 55">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">模版项目设定</div>
                  <!-- <vxe-button
                    type="text"
                    class="button-blue"
                    icon="vxe-icon-save"
                    content="保存"
                    @click="saveMaterialItemList"
                  ></vxe-button> -->
                </template>
                <template #tools>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" :disabled="IsEmpty(templateForm.id)" @click="findTemplateItemList"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="IsEmpty(templateForm.id)" @click="addTemplateItem()"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="保存" :disabled="IsEmpty(templateForm.id)" @click="saveTemplateItem"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="IsEmpty(templateForm.id)" @click="deleteTemplateItem"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="itemTableRef" height="auto" :data="templateItemList" :loading="iloading" :column-config="{ resizable: true }" :edit-config="{
                    trigger: 'click',
                    mode: 'cell',
                    showStatus: false,
                    showIcon: false
                  }" show-overflow keep-source align="left">
                  <vxe-column type="checkbox" width="30"></vxe-column>
                  <vxe-column type="seq" width="30"></vxe-column>
                  <vxe-column field="itemNo" title="项目" :edit-render="{ autofocus: '.vxe-input--inner' }" min-width="100">
                    <template #edit="{ row, rowIndex }">
                      <!-- <SelectDataGrid v-if="row.id === undefined || row.id === '' || row.id === null" :url="'/lis/lab/item/findLabItemDictList'" :column="[
                          { field: 'itemNo', title: '编号' }, //列标题
                          { field: 'itemNa', title: '名称' }
                        ]" :isPage="false" @SelectCellClick="
                          (e) => {
                            SelectRowClick(e, rowIndex);
                          }
                        " :searchParam="{ rptGroup: sltRptGroup && sltRptGroup.code ? sltRptGroup.code : '!@#$%' }">
                      </SelectDataGrid> -->
                      <VxePulldownSelection style="width: 100%" :isChild="false" :childIndex="rowIndex" v-if="row.id === undefined || row.id === '' || row.id === null" :url="'/lis/lab/item/findLabItemDictList'" :tableColumn="[
                          { field: 'itemNo', title: '编号' }, //列标题
                          { field: 'itemNa', title: '名称' }
                        ]" :aimKeys="[
  { aimKey: 'itemNo', rowKey: 'itemNo' },
  { aimKey: 'itemNa', rowKey: 'itemNa' }
]" :displayTexts="['itemNa']" :displayTextObj="row.itemNa ? row.itemNa : ''" @confirmClick="(e) => {
    SelectRowClick(e, rowIndex);
  }
  " :dataObj="{ rptGroup: sltRptGroup && sltRptGroup.code ? sltRptGroup.code : '!@#$%' }" />
                      <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap" v-else>
                        <!-- {{ (!row.exaItem || !row.exaItem.code ? '' : row.exaItem.code) + ' ' + (!row.exaItem || !row.exaItem.name ? '' : row.exaItem.name) }} -->
                        {{ row.itemNo + ' ' + row.itemNa }}
                      </div>
                    </template>

                    <template #default="{ row }">
                      {{ row.itemNo + ' ' + row.itemNa }}
                    </template>
                  </vxe-column>
                  <vxe-column field="typeFlag" title="属性类型" :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{ formatRuleType(row) }}</span>
                    </template>
                    <template #edit="{ row }">
                      <vxe-select v-model="row.typeFlag" placeholder="可清除" clearable>
                        <vxe-option v-for="selectDetail in options" :key="selectDetail.value" :value="selectDetail.value" :label="selectDetail.label"></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="showRowCol" title="展示" :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{ formatRowCols(row) }}</span>
                    </template>
                    <template #edit="{ row }">
                      <vxe-select v-model="row.showRowCol"  placeholder="可清除" clearable>
                        <vxe-option v-for="selectOption in optionRowCols" :key="selectOption.value"
                                    :value="selectOption.value" :label="selectOption.label"></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="typeCode" title="关联模板分类" width="150" :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{ formatCommon(typeCodeList, row.typeCode) }}</span>
                    </template>
                    <template #edit="{ row, rowIndex, column }">
                      <!-- 选择字典  -->
                      <vxe-select v-model="row.typeCode" clearable @change="valueChangeEvent(row)">
                        <vxe-option v-for="hobj in typeCodeList" :key="hobj.id" :value="hobj.code" :label="hobj.name" ></vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="isAssTemplate" title="是否关联模版" width="100" :edit-render="{}">
                    <template #default="{ row }">
                      <el-tag :type="row.isAssTemplate ? 'success' : 'danger'">
                        {{ row.isAssTemplate ? '是' : '否' }}
                      </el-tag>
                    </template>
                    <template #edit="{ row }">
                      <vxe-switch v-model="row.isAssTemplate" open-label="是" close-label="否"></vxe-switch>
                    </template>
                  </vxe-column>
                  <vxe-column field="textHeight" title="文本框高度" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.textHeight" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="detailGroup" title="分组1" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.detailGroup" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="detailGroup2" title="分组2" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.detailGroup2" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <!-- <vxe-column field="rptResult" title="结果" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.rptResult" type="text" clearable @blur="resultChange(row)"></vxe-input>
                    </template>
                  </vxe-column> -->
                  <vxe-column field="seq" title="排序" :edit-render="{ autofocus: '.vxe-input--inner' }" fixed="right" width="60">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.seq" type="text" @blur="seqChange(row)"></vxe-input>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../../stores/store';
import { find, isEmpty } from 'lodash';
import SelectDataList from '@/components/SelectDataList.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';

// 全局变量定义区 ==========
// 获取屏幕高度
let conHeight = ref(document.documentElement.clientHeight);
let useSize = localStorage.getItem('uiSize');

let store = AppStore();
let { proxy }: any = getCurrentInstance();

let rptGroupList: any = reactive([]); //最左侧报告单元表格数据
let templateList: any = reactive([]); //中间模版维护表格
let sltRptGroup: any = reactive({});

let rptGroupLoading = ref(false); //最左侧仪器树形表格加载
let qloading = ref(false); //中间模版维护表格加载

let disabledTag = ref(true); //中间模版维护按钮标记
let iloading = ref(false); //最右侧模版项目设定表格加载

let horizontalList: any = reactive([]); //选择字典

let templateItemList: any = reactive([]); //项目设定表格数据
const orgList = store.userInfo.orgList;
let typeCodeList: any = reactive([]); //左侧对应质控水平选择字典

let searchForm = reactive({
  searchValue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
});
let defaultProps = {
  children: 'children',
  label: 'name'
};

let options = reactive([
  {
    value: '1',
    label: '报告项目'
  },
  {
    value: '1_1',
    label: '可选项目'
  },
  {
    value: '1_2',
    label: '仅项目'
  },
  {
    value: '2',
    label: '描述'
  },
  {
    value: '3',
    label: '结论'
  },
  {
    value: '4',
    label: '图片'
  }
]);

let optionRowCols = reactive([
  {
    value: 'all_row',
    label: '整行展示'
  },
  {
    value: 'right_col',
    label: '左栏展示'
  },
  {
    value: 'left_col',
    label: '右栏展示'
  },
  {
    value: 'auto_col',
    label: '自适应'
  }
]);

let templateForm = reactive({
  id: null,
  templateCode: '',
  templateName: '',
  sampleType: '',
  rptGroup: '',
  isBulkInput: '0',
  isMerge: '0',
  isAutoApply: '0',
  orgId: '',
  seq: 1
});

function formatRuleType(row) {
  const item = options.find((item) => item.value === row.typeFlag);
  return item ? item.label : row.typeFlag;
}
function formatRowCols(row) {
  const item = optionRowCols.find((item) => item.value === row.showRowCol);
  return item ? item.label : row.showRowCol;
}

function handleOrgNodeClick(data: any) {
  searchForm.orgId = data.id;
  searchForm.orgName = data.name;
  findTemplateItemList();
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}

// 清空表单
function clearTemplateForm() {
  templateForm.id = null;
  templateForm.templateCode = '';
  templateForm.templateName = '';
  templateForm.sampleType = '';
  templateForm.rptGroup = '';
  templateForm.isBulkInput = '0';
  templateForm.isMerge = '0';
  templateForm.isAutoApply = '0';
  templateForm.orgId = '';
  templateForm.seq = templateList.length + 1;
  const el: any = proxy.$refs['templateFormRef'];
  //移除校验结果
  el.clearValidate();
}

// 表单校验
let templateFormRule = {
  templateName: [
    {
      required: true,
      message: '请输入模版名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findRptGroupList(); // 获取最左侧 树形表格数据
  getDictItemsList(); //批量获取字典
  findDiagnosTypeList();
});

function getIsStaticStatusDesc(row) {
  if (row.isAutoApply == 0) {
    return '否';
  } else if (row.isAutoApply == 1) {
    return '是';
  }
}
function getIsStaticTagType(row) {
  if (row.isAutoApply == 1) {
    return 'success';
  } else if (row.isAutoApply == 0) {
    return 'danger';
  }
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['QCHORIZONTAL'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'QCHORIZONTAL');
  horizontalList.push(...horizontalType.detailDataList);
}

// 获取左侧仪器下拉选项数据(标题)
function findDiagnosTypeList() {
  const url = '/lab/diagnosType/findParentDiagnosTypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      typeCodeList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 获取最左侧 树形表格数据
function findRptGroupList() {
  rptGroupLoading.value = true;
  rptGroupList.length = 0; //放入数据前清空数据
  const url = '/lab/template/getImgRptGroupTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      rptGroupList.push(...res.data);
      rptGroupLoading.value = false;
      if (rptGroupList.length > 0) {
        const sltObj = getChildren(rptGroupList[0]);
        sltRptGroup = sltObj;
        setCurTypeNode(sltObj);
        clickRowSelect({ row: sltRptGroup }); //点击当前行获取右侧项目表格数据
      }
    })
    .catch((err: any) => {
      rptGroupLoading.value = false;
      VxeMessage('获取最左侧表格数据异常', VxeNotifyType.error);
    });
}

// 光标定位在指定字典分类上
function setCurTypeNode(sltObj: any) {
  proxy.$nextTick(() => {
    const treeName = 'rptGroupTableRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentRow(sltObj);
  });
}
function getChildren(obj: any) {
  const children = obj.children;
  return children[0];
}

// 点击树形表格当前行获取右侧表格数据
function clickRowSelect({ row }) {
  const isSearch = row.isSearch;
  if (isSearch == '0') {
    sltRptGroup = row;
    findTemplateList(); // 右侧获取项目表格数据
  } else {
    templateList.length = 0;
    templateItemList.length = 0;
    clearTemplateForm();
    sltRptGroup = reactive({});
  }
  //如果点击的当前行数据是父级，那就禁用模版维护的按钮
  if (!sltRptGroup.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用模版维护的按钮
    disabledTag.value = false;
  }
}

// 获取中间模版维护数据
function findTemplateList() {
  const el: any = proxy.$refs['templateFormRef'];
  //移除校验结果
  el.clearValidate();
  if (IsEmpty(sltRptGroup)) {
    VxeMessage('请选择报告单元', VxeNotifyType.error);
  } else {
    qloading.value = true;
    templateList.length = 0; //放入数据前清空数据
    const url = '/lab/template/getTemplateByRptGroup';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { rptGroup: sltRptGroup.code, orgId: searchForm.orgId }
      })
      .then((res: any) => {
        templateList.push(...res.data);
        if (templateList.length == 0) {
          clearTemplateForm();
          templateForm.rptGroup = sltRptGroup.code;
          //templateForm.instrName = sltRptGroup.instrName;
          templateItemList.length = 0; //放入数据前清空数据
        } else {
          templateRowClick({ row: templateList[0] }); //默认选中第一条数据
        }
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
      });
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}

// 查询/刷新(关键字)
function handleSearch(row: string | number) {
  qloading.value = true;
  templateList.length = 0; //放入数据前清空数据
  const url = '/lab/template/findTemplates';
  proxy.$http
    .get(url, {
      params: { seachValue: row }
    })
    .then((res: any) => {
      templateList.push(...res.data);
      if (templateList.length == 0) {
        clearTemplateForm();
        templateForm.rptGroup = sltRptGroup.code;
        //templateForm.instrName = sltRptGroup.instrName;
      } else {
        templateRowClick({ row: templateList[0] }); //默认选中第一条数据
      }
      qloading.value = false;
    })
    .catch((err: any) => {
      qloading.value = false;
      VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

// 中间模版维护添加
function addTemplate() {
  if (IsEmpty(sltRptGroup)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    clearTemplateForm();
    templateForm.rptGroup = sltRptGroup.code;
    (proxy.$refs.templateTableRef as any).clearCurrentRow();
    templateItemList.length = 0;
  }
}

// 点击模版当前行触发右侧表单变化
function templateRowClick({ row }: any) {
  if (IsEmpty(row)) {
    clearTemplateForm();
  } else {
    (proxy.$refs.templateTableRef as any).setCurrentRow(row);
    setMaterialForm(row);
  }
}

function setMaterialForm(row: any) {
  Object.assign(templateForm, row);
  findTemplateItemList(); // 获取最右侧 项目设定表格数据
}

// 中间删除按钮
function handleDelete() {
  const sltTemplates = (proxy.$refs.templateTableRef as any).getCheckboxRecords();
  if (!(sltTemplates.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { labTemplateList: sltTemplates };
        const url = '/lab/template/batchDeleteTemplateList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findTemplateList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

//新建
function addTemplateItem() {
  // 如果工作列表结果中已经存在未保存的项，不可重复新增
  const res = templateItemList.find((item) => {
    return IsEmpty(item.id);
  });
  if (res) {
    return;
  }
  // push新的内容
  const $table = proxy.$refs.itemTableRef as any;
  // const newRecord = {}
  // const { row: newRow } =  $table.insert(newRecord)
  // $table.setActiveRow(newRow)

  const newRec = {
    itemNo: '',
    itemNa: '',
    rptResult: '',
    seq: ''
  } as any;
  templateItemList.push(newRec);
  //const { row: newRow } = await $table.insert(newRec)
  $table.reloadData(templateItemList);
  //$table.setEditRow(newRec);
  // proxy.$nextTick(() => {
  //   setTimeout(() => {
  //     $table.scrollToRow(newRec);
  //   }, 50);
  // });
  // 设置新添加行的“检测项目”这一项变为输入框形式
  //this.changeRow(this.workResultList.length - 1, 'anSInputElemt', 'workResultList');
}

function SelectRowClick1(row) {
  templateForm.sampleType = row.sampleTypeCode;
}

// 清空组件输入框
function clearValueHandler() {
  templateForm.sampleType = '';
}
// 键盘事件删除输入框文字
function sliceHandler() {
  let newStr = templateForm.sampleType.slice(0, -1);
  templateForm.sampleType = newStr;
}

function SelectRowClick(e, index) {
  const isExistsObj = templateItemList.filter((p) => p.itemNo === e.row.itemNo);
  if (isExistsObj && isExistsObj.length > 0) {
    VxeMessage('已存在', VxeNotifyType.error);
    return;
  }
  const labTemplateDetail = {
    templateId: templateForm.id,
    itemNo: e.row.itemNo,
    itemNa: e.row.itemNa,
    rptResult: '',
    seq: templateItemList.length + 1
  };
  const url = '/lab/template/detail/updateItemTemplate';
  proxy.$http
    .post(url, labTemplateDetail)
    .then((res: any) => {
      findTemplateItemList(); // 获取最右侧 质控项目设定表格数据
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**结果改变 */
function resultChange(row) {
  const url = '/lab/template/detail/updateTemplateItemInfo';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      findTemplateItemList(); // 获取最右侧 质控项目设定表格数据
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 仪器下拉选择 改变
function valueChangeEvent(row) {
  resultChange(row);
}

function seqChange(row) {
  const url = '/lab/template/detail/updateTemplateItemInfo';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      findTemplateItemList(); // 获取最右侧 质控项目设定表格数据
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 获取最右侧 项目设定表格数据
function findTemplateItemList() {
  iloading.value = true;
  templateItemList.length = 0; //放入数据前清空数据
  const url = '/lab/template/detail/getItemByTemplate';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { id: templateForm.id }
    })
    .then((res: any) => {
      templateItemList.length = 0; //放入数据前清空数据
      templateItemList.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取右侧项目表格数据异常', VxeNotifyType.error);
    });
}

// 最右侧整个表单+表格数据 保存
function saveTemplateAndItem(formName: any) {
  if (IsEmpty(sltRptGroup)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $el = proxy.$refs[formName];
    $el.validate((valid: any) => {
      if (!valid) {
        return false;
      }

      if (templateForm.id === null) {
        const url = '/lab/template/addTemplate';
        const labTemplate = {
          templateCode: templateForm.templateCode,
          templateName: templateForm.templateName,
          sampleType: templateForm.sampleType,
          rptGroup: templateForm.rptGroup,
          isBulkInput: templateForm.isBulkInput,
          isMerge: templateForm.isMerge,
          isAutoApply: templateForm.isAutoApply,
          seq: IsEmpty(templateForm.seq) ? templateList.length + 1 : templateForm.seq
        };
        proxy.$http
          .post(url, labTemplate)
          .then((res: any) => {
            VxeMessage('新增模版成功', VxeNotifyType.success);
            clearTemplateForm();
            findTemplateList();
          })
          .catch((err: any) => {
            VxeMessage('新增模版失败', VxeNotifyType.error);
          });
      } else {
        // 修改信息
        const url = '/lab/template/editTemplate';
        const labTemplate = {
          id: templateForm.id,
          templateCode: templateForm.templateCode,
          templateName: templateForm.templateName,
          sampleType: templateForm.sampleType,
          rptGroup: templateForm.rptGroup,
          isBulkInput: templateForm.isBulkInput,
          isMerge: templateForm.isMerge,
          isAutoApply: templateForm.isAutoApply,
          seq: IsEmpty(templateForm.seq) ? templateList.length + 1 : templateForm.seq
        };
        proxy.$http
          .post(url, labTemplate)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            setTimeout(() => {
              clearTemplateForm();
              findTemplateList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('修改失败', VxeNotifyType.success);
          });
      }
    });
  }
}

// 项目设定 删除
function deleteTemplateItem() {
  const sltMaterialItems = (proxy.$refs.itemTableRef as any).getCheckboxRecords();
  if (!(sltMaterialItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { labTemplateDetailList: sltMaterialItems };
        const url = '/lab/template/detail/batchDeleteTemplateDetailList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findTemplateItemList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

/**保存 */
function saveTemplateItem() {
  let $Xtable = proxy.$refs.itemTableRef;

  if ($Xtable) {
    const updateRecords = $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    const sveOrupdateRules = [] as any[];
    updateRecords.forEach((e: any) => {
      const iIRule: any = {
        id: e.id,
        templateId: e.templateId,
        itemNo: e.itemNo,
        itemNa: e.itemNa,
        rptResult: e.rptResult,
        isAssTemplate: e.isAssTemplate,
        typeCode: e.typeCode,
        textHeight: e.textHeight,
        detailGroup:e.detailGroup,
        detailGroup2:e.detailGroup2,
        typeFlag: e.typeFlag,
        showRowCol: e.showRowCol,
        seq: e.seq
      };
      sveOrupdateRules.push(iIRule);
    });
    console.log(sveOrupdateRules,"sveOrupdateRules");
    if (sveOrupdateRules.length > 0) {
      const url = '/lab/template/detail/batchUpdateTemplateItemInfo';
      const obj: any = {};
      obj.labTemplateDetailList = sveOrupdateRules;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findTemplateItemList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
  // const url = '/lab/template/detail/updateTemplateItemInfo';
  // proxy.$http
  //   .post(url, row)
  //   .then((res: any) => {
  //     findTemplateItemList(); // 获取最右侧 质控项目设定表格数据
  //     VxeMessage(res.status.msg, VxeNotifyType.success);
  //   })
  //   .catch((err: any) => {
  //     VxeMessage(err, VxeNotifyType.error);
  //   });
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
// ------------------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#imgResultTemplate {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }

    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px);
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }

    .el-form {
      padding-right: 15px;

      .el-form-item--large {
        margin-bottom: 10px;
      }
    }

    // 最右侧项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
  }
}
</style>
